package alp.starcode.nudtportal.framework.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class ElasticSearchConfig {
    @Value("${es.userName}")
    private String userName;

    @Value("${es.passwd}")
    private String password;

    @Value("${es.hosts}")
    private String hosts;

    @Bean
    public RestHighLevelClient restClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

        HttpHost[] httpHosts = Arrays.stream(hosts.split(",")).map(x -> {
            String[] hostInfo = x.split(":");
            return new HttpHost(hostInfo[0], Integer.parseInt(hostInfo[1]));
        }).toArray(HttpHost[]::new);
        RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);

        // 设置连接超时、读取超时、请求超时时间
        restClientBuilder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(10000);
            requestConfigBuilder.setSocketTimeout(30000);
            requestConfigBuilder.setConnectionRequestTimeout(10000);
            return requestConfigBuilder;
        });

        // 设置访问es的用户名密码、线程配置
        restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder
                    // 设置用户名密码
                    .setDefaultCredentialsProvider(credentialsProvider)
                    // 配置IO线程
                    .setDefaultIOReactorConfig(IOReactorConfig.custom()
                            .setIoThreadCount(200)
                            .setSoTimeout(10000)
                            .setConnectTimeout(10000)
                            .build()
                    );
            return httpClientBuilder;
        });
        return new RestHighLevelClient(restClientBuilder);
    }
}

